<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Carbon\Carbon;
use App\Models\User;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Collection;

class ArrangeUserLevel extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'cc:arrange-user-level';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command description';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
         User::query()->where('user_level',">",0)->where('vip_expired_at',">",Carbon::now())->chunk(50, function (Collection $users) {

            if ($users->isEmpty()) return false;

            /**
             * @var User $user
             */
            
            foreach ($users as $user) {

                    $date = $user->vipPurchases()->whereNotNull('paid_at')->first()->paid_at;

                    $user->update(['upgrade_at'=>$date->addDays(cs('sale')->detect_days)]);


             }

            return true;

        });
    }
}
